﻿using System;
using System.Text;
using System.Windows.Forms;

namespace PuppetMaster.Menus
{
    public partial class PMMainMenu : Form
    {
        private readonly PuppetMaster _pm;

        private readonly Parser _parser;

        private int _startedServersByGUI;

        public PMMainMenu( PuppetMaster pm )
        {
            _pm = pm;
            _parser = new Parser( pm );
            _startedServersByGUI = 0;

            InitializeComponent( );
        }

        private void buttonBeginReservation_Click( object sender, EventArgs e )
        {
            ListBox.SelectedObjectCollection list = listBoxClients.SelectedItems;
            if( list.Count == 0 )
                return;

            using( ReservationStarter resStarter = new ReservationStarter( ) )
            {
                resStarter.ShowDialog( );
                if( resStarter.DialogResult == DialogResult.Cancel )
                    return;
                foreach( String name in list )
                {
                    string[ ] split = name.Split( ',' );
                    _pm.BeginReservation( split[ 1 ], resStarter.SlotList, resStarter.ClientsToinvite, resStarter.ReservationName );
                }
            }
        }

        private void buttonExecuteScript_Click( object sender, EventArgs e )
        {
            _parser.ParseString( textBoxScript.Text, checkBoxGUI.Checked );
        }

        private void buttonConnectClient_Click( object sender, EventArgs e )
        {
            if( listBoxClients.SelectedItems.Count == 0 )
            {
                string name = generateRandomName( 5 );
                string location = "127.0.0.1:" + generateRandomPort( );

                _pm.ConnectClient( name, location, checkBoxGUI.Checked );

                listBoxClients.Items.Add( String.Format( "[C],{0},{1}", name, location ) );
            }
            else
            {
                ListBox.SelectedObjectCollection list = listBoxClients.SelectedItems;
                int numOfSelected = list.Count;
                string[ ] array = new string[ numOfSelected ];
                list.CopyTo( array, 0 );

                for( int i = 0; i < numOfSelected; ++i )
                {
                    String item = ( String )array[ i ];
                    String[ ] split = item.Split( ',' );

                    _pm.ConnectClient( split[ 1 ], split[ 2 ], checkBoxGUI.Checked );

                    int index = listBoxClients.Items.IndexOf( String.Format( "[D],{0},{1}", split[ 1 ], split[ 2 ] ) );
                    if( index != -1 )
                        listBoxClients.Items[ index ] = String.Format( "[C],{0},{1}", split[ 1 ], split[ 2 ] );
                }
            }
        }

        private void buttonConnectServer_Click( object sender, EventArgs e )
        {
            if( listBoxServers.SelectedItems.Count == 0 )
            {
                if( _startedServersByGUI == 4 )
                    return;
                else
                {
                    int port = _startedServersByGUI + 5001;
                    int serverId = _startedServersByGUI + 1;

                    _pm.ConnectServer( serverId, "127.0.0.1:" + port, checkBoxGUI.Checked );
                    listBoxServers.Items.Add( String.Format( "[C],Server{0},127.0.0.1:{1}", serverId, port ) );
                    _startedServersByGUI++;
                }
            }
            else
            {
                ListBox.SelectedObjectCollection list = listBoxServers.SelectedItems;
                int numOfSelected = list.Count;
                string[ ] array = new string[ numOfSelected ];
                list.CopyTo( array, 0 );

                for( int i = 0; i < numOfSelected; ++i )
                {
                    String item = array[ i ];
                    String[ ] split = item.Split( ',' );

                    _pm.ConnectServer( Int32.Parse( split[ 1 ].Replace( "Server", "" ) ), split[ 2 ], checkBoxGUI.Checked );

                    int index = listBoxServers.Items.IndexOf( String.Format( "[D],{0},{1}", split[ 1 ], split[ 2 ] ) );
                    if( index != -1 )
                        listBoxServers.Items[ index ] = String.Format( "[C],{0},{1}", split[ 1 ], split[ 2 ] );
                }
            }
        }

        private void buttonDisconnectClient_Click( object sender, EventArgs e )
        {
            ListBox.SelectedObjectCollection list = listBoxClients.SelectedItems;
            int numOfSelected = list.Count;
            string[ ] array = new string[ numOfSelected ];
            list.CopyTo( array, 0 );

            for( int i = 0; i < numOfSelected; ++i )
            {
                String item = array[ i ];
                String[ ] split = item.Split( ',' );

                _pm.DisconectClient( split[ 2 ] );

                int index = listBoxClients.Items.IndexOf( String.Format( "[C],{0},{1}", split[ 1 ], split[ 2 ] ) );
                if( index != -1 )
                    listBoxClients.Items[ index ] = String.Format( "[D],{0},{1}", split[ 1 ], split[ 2 ] );
            }
        }

        private void buttonDisconnectServer_Click( object sender, EventArgs e )
        {
            ListBox.SelectedObjectCollection list = listBoxServers.SelectedItems;
            int numOfSelected = list.Count;
            string[ ] array = new string[ numOfSelected ];
            list.CopyTo( array, 0 );

            for( int i = 0; i < numOfSelected; ++i )
            {
                String item = array[ i ];
                String[ ] split = item.Split( ',' );

                _pm.DisconectServer( split[ 2 ] );

                int index = listBoxServers.Items.IndexOf( String.Format( "[C],{0},{1}", split[ 1 ], split[ 2 ] ) );
                if( index != -1 )
                    listBoxServers.Items[ index ] = String.Format( "[D],{0},{1}", split[ 1 ], split[ 2 ] );
            }
        }

        private static string generateRandomName( int size )
        {
            StringBuilder builder = new StringBuilder( );
            Random random = new Random( );
            char ch;
            for( int i = 0; i < size; i++ )
            {
                ch = Convert.ToChar( Convert.ToInt32( Math.Floor( 26 * random.NextDouble( ) + 65 ) ) );
                builder.Append( ch );
            }
            return builder.ToString( );
        }

        private static string generateRandomPort( )
        {
            Random random = new Random( );
            int port = random.Next( 5000, 10000 );
            return port.ToString( );
        }

        private void buttonReadCalendar_Click( object sender, EventArgs e )
        {
            ListBox.SelectedObjectCollection list = listBoxClients.SelectedItems;
            if( list.Count == 0 )
                return;

            foreach( String name in list )
            {
                string[ ] split = name.Split( ',' );
                _pm.ReadCalendar( split[ 2 ], split[ 1 ] );
            }
        }

        private void buttonClearClientList_Click( object sender, EventArgs e )
        {
            listBoxClients.Items.Clear( );
            _pm.KillAllClients( );
        }

        private void buttonClearServerList_Click( object sender, EventArgs e )
        {
            listBoxServers.Items.Clear( );
            _startedServersByGUI = 0;
            _pm.KillAllServers( );
        }

        private void buttonPaste_Click( object sender, EventArgs e )
        {
            if( Clipboard.ContainsText( TextDataFormat.Text ) )
                textBoxScript.Text = Clipboard.GetText( );
        }

        private void loadBtn_Click( object sender, EventArgs e )
        {
            textBoxScript.Clear();
            
            if( openFileDlg.ShowDialog( ) == DialogResult.OK )
            {
                using( System.IO.StreamReader text = new System.IO.StreamReader( openFileDlg.OpenFile( ) ) )
                {
                    String line;
                    while( !text.EndOfStream )
                    {
                        line = text.ReadLine( );
                        textBoxScript.Text = line + System.Environment.NewLine;
                    }
                    text.Close( );
                }
            }
        }
    }
}